package com.phonetools.commonutils.datetime

import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

/**
 * 把String以参数[pattern]格式化成Date，格式化失败时返回默认值[defVal]
 * @param  pattern
 * @param  defVal
 * @return 返回Calendar
 */
fun stringToCalendarOrDef(
    input: String,
    pattern: String = "yyyy-MM-dd HH:mm:ss",
    defVal: Calendar = Calendar.getInstance()
): Calendar {
    val formatter = SimpleDateFormat(pattern, Locale.getDefault())
    return try {
        val date = formatter.parse(input)
        defVal.time = date
        defVal
    } catch (e: ParseException) {
        e.printStackTrace()
        defVal
    }
}

fun yyyyMMddHHmmssToCalendar(input: String): Calendar =
    stringToCalendarOrDef(input, "yyyy-MM-dd HH:mm:ss")

fun yyyyMMddToCalendar(input: String): Calendar =
    stringToCalendarOrDef(input, "yyyy-MM-dd")

fun HHmmssToCalendar(input: String): Calendar =
    stringToCalendarOrDef(input, "HH:mm:ss")

/**
 * 获取当前时间的前一天时间
 * @param input
 * *
 * @return
 */
fun getBeforeDay(input: Calendar): Calendar {
    val day = input.get(Calendar.DATE)
    input.set(Calendar.DATE, day - 1)
    return input
}

/**
 * 获取当前时间的后一天时间
 * @param input
 * *
 * @return
 */
fun getAfterDay(input: Calendar): Calendar {
    val day = input.get(Calendar.DATE)
    input.set(Calendar.DATE, day + 1)
    return input
}

fun getWeekChinese(input: Calendar): String =
    when (input.get(Calendar.DAY_OF_WEEK)) {
        Calendar.SUNDAY -> "周天"
        Calendar.MONDAY -> "周一"
        Calendar.TUESDAY -> "周二"
        Calendar.WEDNESDAY -> "周三"
        Calendar.THURSDAY -> "周四"
        Calendar.FRIDAY -> "周五"
        Calendar.SATURDAY -> "周六"
        else -> ""
    }

fun Calendar.format(
    pattern: String = "yyyy-MM-dd HH:mm:ss",
    timeZone: TimeZone = TimeZone.getDefault()
): String {
    return time.format(pattern = pattern, timeZone = timeZone)
}

fun Calendar.getFirstDayOfMonth() = this.apply {
    val first = getActualMinimum(Calendar.DAY_OF_MONTH)
    set(Calendar.DAY_OF_YEAR, first)
}

fun Calendar.getLastDayOfMonth() = this.apply {
    val last = getActualMaximum(Calendar.DAY_OF_MONTH)
    set(Calendar.DAY_OF_YEAR, last)
}

fun Calendar.getFirstDayOfYear() = this.apply {
    val first = getActualMinimum(Calendar.DAY_OF_YEAR)
    set(Calendar.DAY_OF_YEAR, first)
}

fun Calendar.getLastDayOfYear() = this.apply {
    val last = getActualMaximum(Calendar.DAY_OF_YEAR)
    set(Calendar.DAY_OF_YEAR, last)
}
